package com.renjun.smweb.controller.FileController;

import com.alibaba.fastjson.JSONObject;
import com.renjun.smweb.annotation.AuthorityDeclaration;
import com.renjun.smweb.commons.componet.FileIOComponent;
import com.renjun.smweb.commons.global.DataMap;
import com.renjun.smweb.commons.global.FileInfoPo;
import com.renjun.smweb.commons.util.ResponseUtils;
import com.renjun.smweb.exceptions.BaseException;
import com.renjun.smweb.commons.global.FileInfoPo;
import com.renjun.smweb.exceptions.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * Created by RenJun on 2017/3/1.
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @Autowired
    private FileIOComponent fileIOComponent;

    /**
     * 该方法只用于首页公告文件上传
     *
     * @param file byte
     * @return fileid
     * @author lrs
     */
    @RequestMapping(value = "/uploadNoticeFile", method = RequestMethod.POST)
    @ResponseBody
    @AuthorityDeclaration(id = "uploadNoticeFile", desc = "上传公告文件(zip,7z,tag,rar)")
    public JSONObject uploadNoticeFile(@RequestParam(value = "upfile_attachment") MultipartFile file) {
        try {
            //拼接文件名
            String fileName = file.getOriginalFilename();
            if (fileName == null || "".equals(fileName.trim())) throw new BaseException("文件名称不能为空");
            int postfixIndex = fileName.lastIndexOf(".");       //文件后缀下标
            if (0 == postfixIndex) throw new BaseException("文件类型不合法");
            String postfix = fileName.substring(postfixIndex);  //文件后缀
            fileName = fileName.replace(postfix, "");           //文件名称
            //上传文件
            FileInfoPo fileInfoPo = fileIOComponent.addNewFileByUploadForSuix(file, 6, postfix.replace(".", ""), fileName);
            Map<String, Object> map = new DataMap<>();
            map.put("fileid", fileInfoPo.getId());
            map.put("virpath", fileInfoPo.getFileVirPath());
            return ResponseUtils.createSuccessResponseBody(map);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtils.createErrorResponseBody(e.getMessage());
        }
    }
}
